package com.xyxe.trigger.job;

import com.xyxe.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.xyxe.domain.strategy.service.IRaffleStock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 更新奖品库存任务：为了不让压力给到数据库，采用了redis更新缓存库存，异步队列更新数据库，数据库最终一致
 */
@Slf4j
@Component
public class updateAwardStockJob {
    @Resource
    private IRaffleStock raffleStock;

    @Scheduled(cron = "0/5 * * * * ?")
    public void execute() {
        try{
            log.info("定时任务，更新奖品消耗库存【延迟队列获取，降低对数据库的更新频次，不要产生竞争】");
            StrategyAwardStockKeyVO strategyAwardStockKeyVO = raffleStock.takeQueueValue();
            if (strategyAwardStockKeyVO == null) return;
            log.info("定时任务，更新奖品消耗库存 strategyId: {}  awardId:{}", strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());
            raffleStock.updateStrategyAwardStock(strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());

        } catch (InterruptedException e) {
            log.error("定时任务更新奖品库存失败", e);
        }
    }
}
